import React, { useCallback } from 'react';
import {
  CalculateFuncs,
  CalculateOperators,
  ICalculateType,
  IEditorRefHandles,
  IEditorType,
} from './CodeEditorConfig';
import { CodeEditorToolbar } from './CodeEditorToolbar';

interface Props {
  editor?: IEditorRefHandles;
  editorType?: IEditorType;
  readOnly?: boolean;
  isFunc?: boolean;
  className?: string;
  style?: React.CSSProperties;
}

/** 计算函数/操作符 */
export const CodeEditorCalculate: React.FC<Props> = (props) => {
  const { editor, editorType, readOnly, isFunc, className, style } = props;

  /** 编辑器事件，这里可以根据需要拓展editorEvent中的方法 */
  const onCalculateChange = useCallback(
    (value: ICalculateType) => {
      let val: string = value;

      if (readOnly) {
        return;
      }

      if (isFunc) {
        val = `${value}()`;
        if (value === 'count(distinct concat())') {
          val = value;
        }

        if (value === 'count(distinct)') {
          val = 'count(distinct )';
        }
      }

      editor && editor.insert(val);
    },
    [readOnly, editor, isFunc],
  );

  return (
    <CodeEditorToolbar
      shape={isFunc ? 'round' : 'default'}
      type={isFunc ? 'default' : 'link'}
      size={isFunc ? undefined : 'small'}
      data={[isFunc ? CalculateFuncs : CalculateOperators]}
      callback={(value) => onCalculateChange(value)}
      className={className}
      style={{ ...style, padding: isFunc ? '8px 0' : '' }}
    />
  );
};
